package com.ruoyi.restaurant.controller;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.restaurant.domain.Menu;
import com.ruoyi.restaurant.service.IRestMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/restaurant/menu")
public class RestaurantController extends BaseController {
    @Autowired
    private IRestMenuService menuService;

    /**
     * 菜单列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Menu menu) {
        startPage();
        List<Menu> list = menuService.getMenuList(menu);
        return getDataTable(list);
    }

    /**
     * 查询所有菜单（不分页，用于点单）
     */
    @GetMapping("/all")
    public AjaxResult listAll(Menu menu) {
        // 只查询状态为正常售卖的菜单（status='0'表示正常）
        menu.setStatus("1");
        List<Menu> list = menuService.getMenuList(menu);
        return success(list);
    }

    /**
     * 获取菜单详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(menuService.getMenuById(id));
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(menuService.deleteMenuById(id));
    }
    /*
    * 批量删除
    * */
    @PostMapping("/deleteLists")
//    数组类型的ids
    public AjaxResult removes(@RequestBody  Object params) {
        return toAjax(menuService.deleteMenuByIds(params));
//        return toAjax(menuService.deleteMenuByIds(params.ids));
    }
    /**
     * 新增菜单
     */
    @PostMapping()
    public AjaxResult add(@RequestBody Menu menu) {
        return toAjax(menuService.insertMenu(menu));
    }
    /**
     * 修改菜单
     */
    @PutMapping()
    public AjaxResult edit(@RequestBody Menu menu) {
        return toAjax(menuService.updateMenu(menu));
    }

    /*
    * 导出
    *
    */
    @PostMapping("/export")
    void export(HttpServletResponse response, Menu menu)
    {
        startPage();
        List<Menu> list = menuService.getMenuList(menu);
        System.out.println(list);
        ExcelUtil<Menu> util = new ExcelUtil<Menu>(Menu.class);
        util.exportExcel(response, list, "菜单");
    }
    /*
    * 下载导入模板
    *
    */
    @PostMapping("/importTemplate")
    void importTemplate(HttpServletResponse response){
        ExcelUtil<Menu> util = new ExcelUtil<Menu>(Menu.class);
        util.importTemplateExcel(response, "菜单");

    }

    /**
     * 导入菜单数据
     */
    @Log(title = "菜单管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('restaurant:menu:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        // 文件验证
        if (StringUtils.isNull(file) || file.isEmpty())
        {
            return error("上传文件不能为空");
        }

        // 文件类型验证
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName) || !fileName.toLowerCase().endsWith(".xlsx") && !fileName.toLowerCase().endsWith(".xls"))
        {
            return error("请上传Excel格式的文件");
        }

        try
        {
            ExcelUtil<Menu> util = new ExcelUtil<Menu>(Menu.class);
            List<Menu> menuList = util.importExcel(file.getInputStream());

            // 获取当前操作用户
            String operName = getUsername();

            // 调用菜单服务的导入方法
            String message = menuService.importMenu(menuList, updateSupport, operName);
            return success(message);
        }
        catch (Exception e)
        {
            logger.error("导入菜单数据失败", e);
            return error("导入失败：" + e.getMessage());
        }
    }
}
